package com.it.commicity.service.impl.sys;

import com.aliyun.oss.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.it.commicity.common.Result;
import com.it.commicity.common.ResultCodeEnum;
import com.it.commicity.config.oss.OSSUtil;
import com.it.commicity.domain.po.SysUser;
import com.it.commicity.domain.requestPass.Password;
import com.it.commicity.domain.vo.SysUserVo;
import com.it.commicity.domain.vo.user.SysUserDto;
import com.it.commicity.mapper.sys.SysUserMapper;
import com.it.commicity.service.sys.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.it.commicity.utils.JwtUtils;
import com.it.commicity.utils.JwtUtils;
import com.it.commicity.utils.RedisConstants;
import com.it.commicity.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserDao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<SysUserVo> login(SysUser sysUser) {
        SysUser user = sysUserDao.login(sysUser.getUserName());
        SysUserVo<SysUser> userVo = new SysUserVo<>();
        //判断用户是否为空
        if (user == null) {
            return Result.fail(ResultCodeEnum.FAIL);
        }
        //判断登入时密码明文和密文是否一致
        boolean matches = passwordEncoder.matches(sysUser.getPassword(), user.getPassword());
        //验证密码和账户正确
        if (matches) {
            String jwtToken = JwtUtils.getJwtToken(user.getUserId() + "", user.getUserName());
//            System.err.println("登录获取到的token=》" + jwtToken);
            //1 判断是否被删除
            if ("0".equals(user.getDelFlag())) {
                //判断是否被禁用
                if ("0".equals(user.getStatus())) {
                    userVo.setCode(200);
                    userVo.setMsg("登入成功！");
                    userVo.setData(user);
                    userVo.setToken(jwtToken);
                } else {
                    return Result.fail("该账号已被停用！");
                }
            }
            //1 被删除
            else {
                return Result.fail("该账户已被注销！");
            }

        } else {
            return Result.fail("账号密码错误！");
        }
        LambdaUpdateWrapper<SysUser> qw = new LambdaUpdateWrapper<>();
        qw.set(SysUser::getLoginDate, LocalDateTime.now())
                .eq(SysUser::getUserId, user.getUserId());
        sysUserDao.update(null, qw);
        return Result.success(userVo);
    }

    @Override
    public SysUserDto queryByUserId(Long userId) {
        return sysUserDao.queryByUserId(userId);
    }

    @Override
    public int updateUserImageByUserId(String userId, String image) {
        SysUser user = sysUserDao.selectById(userId);
        String avatar = user.getAvatar();
        if (!StringUtils.isNullOrEmpty(avatar)) {
            OSSUtil.deleteImageByUrl(avatar);
        }
        return sysUserDao.updateUserImageByUserId(Long.valueOf(userId), image);
    }

    @Override
    public Result updateUserByUserId(SysUser user) {
        if (!user.getUserId().equals(UserHolder.getUser().getUserId())) {
            return Result.fail(ResultCodeEnum.USER_LOGIN_MISMATCH);
        }
//        LambdaUpdateWrapper<SysUser> luw = new LambdaUpdateWrapper();
//        luw.eq(SysUser::getUserId, user.getUserId());
        //数据校验
//        if (!StringUtils.isNullOrEmpty(user.getNickName())) {
//            luw.set(SysUser::getNickName, user.getNickName());
//        }
//        if (!StringUtils.isNullOrEmpty(user.getPhonenumber())) {
//            luw.set(SysUser::getPhonenumber, user.getPhonenumber());
//        }
//        if (!StringUtils.isNullOrEmpty(user.getEmail())) {
//            luw.set(SysUser::getEmail, user.getEmail());
//        }
//        if (!StringUtils.isNullOrEmpty(user.getSex())) {
//            luw.set(SysUser::getSex, user.getSex());
//        }
//        int i = sysUserDao.update(null, luw);
//        System.err.println(user);
        int i = sysUserDao.updateById(user);
        if (i <= 0) {
            return Result.fail(ResultCodeEnum.USER_LOGIN_MISMATCH);
        }
        return Result.success("更新成功");
    }

    @Override
    public Result updateUserPasswordByUserId(Password password) {
        if (!password.getNewPassword().equals(password.getConfirmPassword())) {
            return Result.fail("两次密码不一致");
        }
        Long userId = UserHolder.getUser().getUserId();
        SysUser user = sysUserDao.selectById(userId);
        if (user == null) {
            return Result.fail("请重新登录");
        }
        // 前后端密码是否一致
//        System.out.println("tt");
        if (!passwordEncoder.matches(password.getOldPassword(), user.getPassword())) {
            return Result.fail("密码错误");
        }
        // 新密码是否与旧密码一样
        if (passwordEncoder.matches(password.getNewPassword(), user.getPassword())) {
            return Result.fail("新密码与旧密码一致");
        }
        String key = RedisConstants.LOGIN_CODE_KEY + password.getPhone();
//        System.out.println("tt");
        String code = stringRedisTemplate.opsForValue().get(key);
//        System.out.println("tt");
        //redis验证码是否存在
        if (!org.springframework.util.StringUtils.hasLength(code)) {
            //不存在
            return Result.fail("验证码已过期！");
        }
        if (!password.getCode().equals(code)) {
            return Result.fail("验证码错误！");
        }
//        System.out.println("tt");
        if (!user.getPhonenumber().equals(password.getPhone())) {
            sysUserDao.updatPhoneByUserId(password.getPhone(), userId);
        }
//        System.out.println("tt");
//        sysUserDao.updateUserPasswordByUserId(passwordEncoder.encode(password.getNewPassword()), userId);
        SysUser updateUser = new SysUser();
        updateUser.setUserId(userId);
        updateUser.setPassword(passwordEncoder.encode(password.getNewPassword()));
        sysUserDao.updateById(updateUser);
//        System.out.println("tt");
        return Result.success("更新成功");
    }
}
